<?php
require_once('../../core.inc.php');
require_once('Model/SiteManage.php');
require_once('View/Smarty.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
require_once('Model/Uploader.php');
require_once('Model/Pager.php');
require_once('Plugin/Banner.php');

$sys = new Model_SiteManage();
$sys->checkLogin();
$params = $_REQUEST;
$smarty = new View_Smarty($params);
$banner = new Model_banner();
$smarty->assign('banner', $banner);

if (isset($params['do']) && function_exists('exec_' . $params['do'])){
   $params['op'] = call_user_func('exec_' . $params['do'], &$params, &$smarty, &$banner);
}
if (isset($params['op']) && function_exists('op_' . $params['op'])){
    call_user_func('op_' . $params['op'], $params, &$smarty, &$banner);
}
else{
    call_user_func('op_search', $params, &$smarty, &$banner);
}


function op_search($params, &$smarty, &$banner)
{
    /** バナー種別(banner_type)読込み **************************************************/
    $db = new Model_DB;
    $arrColumn = array();
    $sql = sprintf( "SELECT * FROM M_BANNER WHERE site = %u ORDER BY order_num", $banner->sys->getCurrentSite());
    $db->query( $sql );
    if( $db->num_rows() ){
            while( $row = $db->fetch() ){
                    $arrColumn[$row['id']] = $row['name'];
            }
    }

    if( isset($params['y']) && isset($params['m']) ){

            if( !is_numeric($params['y']) ) exit; if( !is_numeric($params['m']) ) exit;
            if( !checkdate( $params['m'], 1, $params['y'] ) ) exit;

            $year = $params['y']; $month = $params['m'];

    }else{

            $current_ym = time();
            $year = date("Y", $current_ym); $month = date("n", $current_ym);
    }

    $current_date = mktime(0, 0, 0, $month, 1, $year);
    while( date("w", $current_date ) ){
            $current_date -= 60 * 60 * 24;
    }
    
    /** 先月末尾部分作成   **********************************************/
    $i = 0;
    $prevMonth = array();
    while( date("d", $current_date) != 1 ){
            $prevMonth[$i]['date'] = date("Y-m-d", $current_date);
            $prevMonth[$i]['day'] = date("d", $current_date);
            if( date("w", $current_date) == 6) $prevMonth[$i]['sat'] = true;
            if( date("w", $current_date) == 0) $prevMonth[$i]['sun'] = true;
            $current_date += 60 * 60 * 24;
            $i++;
    }

    /** 今月カレンダー作成   **********************************************/
    $thisMonth = array();
    while( date("n", $current_date) == $month ){
            $dt = date("Y-m-d", $current_date);
            $thisMonth[$dt]['day'] = date("j", $current_date);
            foreach( $arrColumn as $k => $v ){
                    $thisMonth[$dt]['banner'][$k] = '';
            }

            if( date("w", $current_date) == 6) $thisMonth[$dt]['sat'] = true;
            if( date("w", $current_date) == 0) $thisMonth[$dt]['sun'] = true;
            $current_date += 60 * 60 * 24;
    }
    
    /** 次月先頭部分作成   **********************************************/
    $i = 0;
    $nextMonth = array();
    while( date("w", $current_date) != 0 ){
            $nextMonth[$i]['date'] = date("Y-m-d", $current_date);
            $nextMonth[$i]['day'] = date("j", $current_date);
            if( date("w", $current_date) == 6) $nextMonth[$i]['sat'] = true;
            if( date("w", $current_date) == 0) $nextMonth[$i]['sun'] = true;
            $current_date += 60 * 60 * 24;
            $i++;
    }
    
    // 公開中で最新のモノをサーチ
    foreach( $arrColumn as $k => $v ){
            $arrBanner[$k] = '';
    }
    $db = new Model_DB();
    $sql = sprintf( "SELECT DATE_FORMAT(banner_date,'%%Y-%%m-%%d') AS b_date, banner_date AS banner_time, banner_type
                     FROM D_BANNER
                     WHERE site = %u AND banner_date <= CURRENT_TIMESTAMP AND status = '1'
                     ORDER BY banner_date DESC", $banner->sys->getCurrentSite() );
    $db->query( $sql );
    while( $row = $db->fetch() ){
            if( isset( $arrBanner[ $row['banner_type'] ] ) && $arrBanner[ $row['banner_type'] ] == '' ){
                    $arrBanner[ $row['banner_type'] ] = $row['b_date'];
            }
    }
    $arrKeys = array_keys( $thisMonth );
    $firstday = $arrKeys[0];
    $lastday = $arrKeys[ count($arrKeys) -1 ];

    $sql = sprintf("SELECT DATE_FORMAT(banner_date,'%%Y-%%m-%%d') AS b_date, banner_date AS banner_time, banner_type, status
                    FROM D_BANNER 
                    WHERE banner_date BETWEEN '%s 00:00:00' AND '%s 23:59:59'", $firstday, $lastday );

    $db->query( $sql );
    while( $row = $db->fetch() )
    {            
        // バナータイプが公開中のモノ
//        if( array_key_exists( $row['banner_type'], $arrColumn ) )
//        {
//            if( $row['banner_time'] > date("Y-m-d H:i:s") ){
//                    $thisMonth[ $row['b_date'] ]['banner'][ $row['banner_type'] ] = 2;		//準備中
//            }else{
//                if( $arrBanner[ $row['banner_type'] ] == $row['b_date'] ){//$arrBanner 公開中でbanner_dateが最新のモノ
//                        $thisMonth[ $row['b_date'] ]['banner'][ $row['banner_type'] ] = 1;	//公開中
//                }else{
//                        $thisMonth[ $row['b_date'] ]['banner'][ $row['banner_type'] ] = 3;	//その他(ステータスが公開でも、banner_dateが新しいものがあればこれになる)
//                }
//            }
//        }
        
        //↓D_BANNERのstatusを見るように変更
        $thisMonth[ $row['b_date'] ]['banner'][ $row['banner_type'] ] = $row['status'];

    }
        //var_dump($thisMonth);exit;
    // 前月・次月リンク
    $tmpdate = mktime(0, 0, 0, $month - 1, 1, $year);
    $smarty->assign('year_prev', date("Y", $tmpdate) );
    $smarty->assign('month_prev', date("n", $tmpdate) );

    $tmpdate = mktime(0, 0, 0, $month + 1, 1, $year);
    $smarty->assign('year_next', date("Y", $tmpdate) );
    $smarty->assign('month_next', date("n", $tmpdate) );

    $smarty->assign('arrColumn', $arrColumn );

    $smarty->assign('year', $year );
    $smarty->assign('month', $month );
    $smarty->assign('prevMonth', $prevMonth );
    $smarty->assign('thisMonth', $thisMonth );
    $smarty->assign('nextMonth', $nextMonth );
    
    $smarty->display('banner/banner_index.html');
}

// 新規登録
function op_regist($params, &$smarty, &$banner)
{
    /** バナー種別(banner_type)読込み **************************************************/
    $db = new Model_DB;
    $arrColumn = array();
    $sql = sprintf( "SELECT * FROM M_BANNER WHERE site = %u ORDER BY order_num", $banner->sys->getCurrentSite() );
    $db->query( $sql );
    if( $db->num_rows() ){
            while( $row = $db->fetch() ){
                    $arrColumn[$row['id']] = $row['name'];
            }
    }
    
    if (!isset($params['forms'])){
        $forms = array();
        foreach($banner->getFormKeys() as $key){
            $forms[$key] = '';
        }

        //デフォルト値
        $forms['banner_type'] =  $params['b'];//banner_type
        $forms['banner_date'] = sprintf("%s-%s-%s", $params['y'], $params['m'], $params['d'] );
        $forms['status'] = 1;
        $forms['interval1'] = 5;
        $forms['temp_name'][0] = '';
        $forms['target'][0] = 0;
                
        $params['forms'] = $forms;
    }

    $smarty->assign('arrColumn',    $arrColumn);
    $smarty->assign('status',    $banner->getStatusMap() );
    $smarty->assign('target',    $banner->getTargetMap());
    $smarty->assign('animation', $banner->getAnimationMap());
    $smarty->assign('time',      $banner->getTimeMap());

    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('banner/banner_form.html');
}

function exec_validate_regist_form(&$params, &$smarty, &$banner)
{
    $err = array();
    
    // ファイルアップロード(tmp)
    if( $params['mode'] == 'upload' )
    {
        $uploader = new Model_Uploader();

        if( is_array( $_FILES['image']['error'] ) )
        {
                foreach( $_FILES['image']['error'] as $k => $v )
                {
                        if( $v == 1 ){
                                $err['image'][$k] = 'ファイルサイズ大きいため、アップロードができませんでした';
                                $params['forms']['temp_name'][$k] = '';
                        }elseif( $v == 0 ){
                                $ext = strtolower( getext( $_FILES['image']['name'][$k] ) );//アップロードファイル名から拡張子取得
                                switch( $ext ){
                                    case '.jpg':
                                    case '.jpeg':
                                    case '.gif':
                                    case '.png':
                                        $is_img = 1;
                                        break;
                                    default:
                                        $is_img = 9;
                                }

                                if( $is_img == 9 ){//使用できない拡張子
                                        $err['image'][$k] = 'アップロードしたファイルは扱えませんでした';
                                        $params['forms']['temp_name'][$k] = '';
                                }else{
                                        if( is_uploaded_file($_FILES['image']['tmp_name'][$k]) ){//テンポラリファイル名
                                            $tmp_name = md5( microtime() ) . strtolower( getext( $_FILES['image']['name'][$k]) );
                                            move_uploaded_file( $_FILES['image']['tmp_name'][$k], $uploader->cache_dir. $tmp_name);
                                            $params['forms']['temp_name'][ $k ] = $tmp_name;
                                            //$params['forms']['original'][ $k ] = $_FILES['image']['name'][$k];//アップロードファイル名
                                        }
                                }
                        }
                }
        }
    }
    elseif ($banner->validate($params['forms'], $err)){
        return exec_regist_form($params, $smarty, $banner);
    }

    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);

    return 'regist';
}
function exec_regist_form(&$params, &$smarty, &$banner)
{   
    // カレンダー戻り時のパラメタ
    $tmp_date = explode('-', $params['forms']['banner_date'] );
    $year = $tmp_date[0];
    $month = (int)$tmp_date[1];
    $day = (int)$tmp_date[2];
    
    $params['forms']['banner_date'] = $params['forms']['banner_date'] . ' ' . $params['forms']['st_time'] . ':00:00';
    $params['forms']['site'] = $banner->sys->getCurrentSite();
    
    $id = $banner->insert($params['forms']);
    
    // ファイルアップロード(tmp->img_dir)
    $db = new Model_DB();
    $sql = sprintf("DELETE FROM D_IMAGE WHERE func = %u AND id = %u", $banner->config['id'], $id);
    $db->query( $sql );
    $uploader = new Model_Uploader();
    foreach( $params['forms']['temp_name'] as $order_num => $temp_name )
    {
        $fname = $id.'_'.$order_num;//$uploader->moveCacheImage使うなら拡張子不要
        $move_to = $banner->getSiteDir($mkdir = true).'files/banner/';
        if(!file_exists($move_to)){
            $banner->sys->createDir($move_to);
        }
        $fname_ext = $uploader->moveCacheImage($temp_name, $move_to, $fname);//拡張子つきファイル名

        $sql = sprintf( "INSERT INTO D_IMAGE( func, id, order_num, alt_text, url, target, filename ) VALUES( %u, %u, %u, '%s', '%s', '%s', '%s' )",
                $banner->config['id'],
                $id,
                $order_num,
                $db->escape( $params['forms']['alt_text'][$order_num] ),
                $db->escape( $params['forms']['url'][$order_num] ),
                $params['forms']['target'][$order_num],
                $fname_ext
        );
        $db->query( $sql );
    }
    
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=regist_complete&id=' . $id.'&y='.$year.'&m='.$month.'&d='.$day.'&b='.$params['forms']['banner_type']);
    exit();
}

function op_regist_complete($params, &$smarty, &$banner)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $smarty->assign('year', $params['y']);
        $smarty->assign('month', $params['m']);
        $smarty->assign('day', $params['d']);
        $smarty->assign('banner_type', $params['b']);
    }
    $smarty->assign('message', '登録が完了しました');
    $smarty->display('banner/banner_form.html');
}

// 編集
function op_edit($params, &$smarty, &$banner)
{    
    /** バナー種別(banner_type)読込み **************************************************/
    $db = new Model_DB;
    $arrColumn = array();
    $sql = sprintf( "SELECT * FROM M_BANNER WHERE site = %u ORDER BY order_num", $banner->sys->getCurrentSite() );
    $db->query( $sql );
    if( $db->num_rows() ){
            while( $row = $db->fetch() ){
                    $arrColumn[$row['id']] = $row['name'];
            }
    }
    
    if (!isset($params['forms']) or !isset($params['id'])){
        
        if( !(isset($params['y']) && is_numeric($params['y'])) ) __raise_error();
        if( !(isset($params['m']) && is_numeric($params['m'])) ) __raise_error();
        if( !(isset($params['d']) && is_numeric($params['d'])) ) __raise_error();
        if( !checkdate( $params['m'], $params['d'], $params['y'] ) ) __raise_error();

        $banner_date = sprintf("%s-%s-%s", $params['y'], $params['m'], $params['d'] );
        $banner_type = $params['b'];

        $db = new Model_DB;
        $sql = "SELECT id, DATE_FORMAT(banner_date,'%Y-%m-%d') AS banner_date, DATE_FORMAT(banner_date,'%k') AS st_time, banner_type, status, animation, interval1, r_date, u_date " . 
        sprintf( "FROM D_BANNER WHERE site = %u AND banner_date BETWEEN '%s 00:00:00' AND '%s 23:59:59' AND banner_type = '%s'",
                        $banner->sys->getCurrentSite(), $banner_date, $banner_date, $banner_type
                );
        $db->query( $sql );
        
        $forms = $db->fetch();

        // テンポラリファイル作成
        // 画像
        $uploader = new Model_Uploader();
        $sql = sprintf("SELECT * FROM D_IMAGE WHERE func = %u AND id = %u ORDER BY order_num ASC", $banner->config['id'], $forms['id']);
        $db->query( $sql );
        if( $db->num_rows() ){
            while( $row = $db->fetch() ){
                $tmp_name = 'banner' . md5( microtime() ) . '_' . $row['order_num'] . getext( $row['filename'] );
                $img_dir = $banner->getSiteDir().'files/banner/';
                if( file_exists( $img_dir . $row['filename'] ) )
                {
                    copy( $img_dir . $row['filename'], $uploader->cache_dir . $tmp_name );
                    $forms['temp_name'][ $row['order_num'] ] = $tmp_name;
                    $forms['alt_text'][ $row['order_num'] ] = $row['alt_text'];
                    $forms['url'][ $row['order_num'] ] = $row['url'];
                    $forms['target'][ $row['order_num'] ] = $row['target'];
                }
            }
        }
        $params['forms'] = $forms;
        $id = $forms['id'];
    }
    else
    {
        $id = $params['id'];
    }

    $smarty->assign('arrColumn',    $arrColumn);
    $smarty->assign('status',    $banner->getStatusMap() );
    $smarty->assign('target',    $banner->getTargetMap());
    $smarty->assign('animation', $banner->getAnimationMap());
    $smarty->assign('time',      $banner->getTimeMap());
    
    $smarty->assign('id', $id);
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('banner/banner_form.html');
}

function exec_validate_edit_form(&$params, &$smarty, &$banner)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    if ($params['mode'] == 'delete')
    {
        return exec_delete_form($params, $smarty, $banner);
    }
    
    $err = array();
    
    // ファイルアップロード(tmp)
    if( $params['mode'] == 'upload' )
    {
        $uploader = new Model_Uploader();
        
        if( is_array( $_FILES['image']['error'] ) )
        {
                foreach( $_FILES['image']['error'] as $k => $v )
                {
                        if( $v == 1 ){
                                $err['image'][$k] = 'ファイルサイズ大きいため、アップロードができませんでした';
                                $params['forms']['temp_name'][$k] = '';
                        }elseif( $v == 0 ){
                                $ext = strtolower( getext( $_FILES['image']['name'][$k] ) );//アップロードファイル名から拡張子取得
                                switch( $ext ){
                                    case '.jpg':
                                    case '.jpeg':
                                    case '.gif':
                                    case '.png':
                                        $is_img = 1;
                                        break;
                                    default:
                                        $is_img = 9;
                                }

                                if( $is_img == 9 ){//使用できない拡張子
                                        $err['image'][$k] = 'アップロードしたファイルは扱えませんでした';
                                        $params['forms']['temp_name'][$k] = '';
                                }else{
                                        if( is_uploaded_file($_FILES['image']['tmp_name'][$k]) ){//テンポラリファイル名
                                            $tmp_name = md5( microtime() ) . strtolower( getext( $_FILES['image']['name'][$k]) );
                                            move_uploaded_file( $_FILES['image']['tmp_name'][$k], $uploader->cache_dir. $tmp_name);
                                            $params['forms']['temp_name'][ $k ] = $tmp_name;
                                            //$params['forms']['original'][ $k ] = $_FILES['image']['name'][$k];//アップロードファイル名
                                        }
                                }
                        }
                }
        }
    }
    elseif ($banner->validate($params['forms'], $err)){
        return exec_edit_form($params, $smarty, $banner);
    }

    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'edit';
}
function exec_edit_form(&$params, &$smarty, &$banner)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $id = $params['id'];

    // カレンダー戻り時のパラメタ
    $tmp_date = explode('-', $params['forms']['banner_date'] );
    $year = $tmp_date[0];
    $month = (int)$tmp_date[1];
    $day = (int)$tmp_date[2];
    
    $params['forms']['banner_date'] = $params['forms']['banner_date'] . ' ' . $params['forms']['st_time'] . ':00:00';
    $params['forms']['site'] = $banner->sys->getCurrentSite();

    $banner->update($id, $params['forms']);
    
    
    // ファイルアップロード(tmp->img_dir)
    $db = new Model_DB();
    $sql = sprintf("DELETE FROM D_IMAGE WHERE func = %u AND id = %u", $banner->config['id'], $id);
    $db->query( $sql );
    $uploader = new Model_Uploader();
    foreach( $params['forms']['temp_name'] as $order_num => $temp_name )
    {
        $fname = $id.'_'.$order_num;//$uploader->moveCacheImage使う場合、拡張子不要(自動的に付加される)
        $move_to = $banner->getSiteDir($mkdir = true).'files/banner/';
        if(!file_exists($move_to)){
            $banner->sys->createDir($move_to);
        }
        $fname_ext = $uploader->moveCacheImage($temp_name, $move_to, $fname);//拡張子つきファイル名

        $sql = sprintf( "INSERT INTO D_IMAGE( func, id, order_num, alt_text, url, target, filename ) VALUES( %u, %u, %u, '%s', '%s', '%s', '%s' )",
                $banner->config['id'],
                $id,
                $order_num,
                $db->escape( $params['forms']['alt_text'][$order_num] ),
                $db->escape( $params['forms']['url'][$order_num] ),
                $params['forms']['target'][$order_num],
                $fname_ext
        );
        $db->query( $sql );
    }

    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=edit_complete&id=' . $id.'&y='.$year.'&m='.$month.'&d='.$day.'&b='.$params['forms']['banner_type']);
    exit();
}
function op_edit_complete($params, &$smarty, &$banner)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $smarty->assign('year', $params['y']);
        $smarty->assign('month', $params['m']);
        $smarty->assign('day', $params['d']);
        $smarty->assign('banner_type', $params['b']);
    }
    $smarty->assign('message', '更新が完了しました');
    $smarty->display('banner/banner_form.html');
}

function exec_delete_form(&$params, &$smarty, &$banner)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    
    $row = $banner->get($params['id']);
    // カレンダー戻り時のパラメタ
    $tmp_date = explode('-', $row['banner_date'] );
    $year = $tmp_date[0];
    $month = (int)$tmp_date[1];
    
    $res = $banner->delete($params['id']);
    if($res)
    {
        //ファイル削除
    }
                
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=delete_complete&id=' . $id.'&y='.$year.'&m='.$month);
    exit();
}
function op_delete_complete($params, &$smarty, &$banner)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['y'])){
        $smarty->assign('year', $params['y']);
        $smarty->assign('month', $params['m']);
    }
    $smarty->assign('message', '削除が完了しました');
    $smarty->display('banner/banner_form.html');
}

function op_preview($params, &$smarty, &$banner)
{
    if( !(isset($params['y']) && is_numeric($params['y'])) ) __raise_error();
    if( !(isset($params['m']) && is_numeric($params['m'])) ) __raise_error();
    if( !(isset($params['d']) && is_numeric($params['d'])) ) __raise_error();
    if( !checkdate( $params['m'], $params['d'], $params['y'] ) ) __raise_error();

    $banner_date = sprintf("%s-%s-%s", $params['y'], $params['m'], $params['d'] );
    $banner_type = $params['b'];

    $db = new Model_DB;
    $sql = "SELECT id, DATE_FORMAT(banner_date,'%Y-%m-%d') AS banner_date, DATE_FORMAT(banner_date,'%k') AS st_time, banner_type, status, animation, interval1, r_date, u_date " . 
    sprintf( "FROM D_BANNER WHERE site = %u AND banner_date BETWEEN '%s 00:00:00' AND '%s 23:59:59' AND banner_type = '%s'",
                    $banner->sys->getCurrentSite(), $banner_date, $banner_date, $banner_type
            );
    $db->query( $sql );
    $forms = $db->fetch();
    
    $sql = sprintf("SELECT * FROM D_IMAGE WHERE func = %u AND id = %u ORDER BY order_num ASC", $banner->config['id'], $forms['id']);
    $db->query( $sql );
    if( $db->num_rows() ){
        while( $row = $db->fetch() ){
            $forms['file_url'][ $row['order_num'] ] = $banner->getSiteUrl()."files/banner/".$row['filename'];
        }
    }
    $smarty->assign('forms', $forms);
    $smarty->display('banner/banner_preview.html');
}

// 拡張子取得
function getext( $filename ){
	
	if( strpos( $filename, "." ) ){
		$tmp = explode('.', $filename );
		return '.' . end( $tmp );
	}else{
		return '';
	}
	
}
?>